<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Admin\Controller as Controller1;
use App\Models\Order;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use App\Models\User;

class UserController extends Controller1
{
    //
    //获取用户列表
    public function getUserList(Request $request){
        $name = $request->name; //姓名
        $mobile = $request->mobile;//手机号码
        //$status = $request->status; //用户状态  正常  禁用
        $start_time = $request->start_time;
        $end_time = $request->end_time;

        $where = function($query) use ($request){
            if($request->name){
                $query->where('name','like', '%'.$request->name.'%');
            }
            if($request->mobile){
                $query->where('mobile','like', '%'.$request->mobile.'%');
            }
//            if($request->status==='0'||$request->status==='1'){
//                $query->where('status',$request->status);
//            }
            if($request->start_time&&$request->end_time){
                $query->whereBetween('created_at',[$request->start_time,$request->end_time]);
            }
        };

//        $name&&$where['name'] = $name;
//        $phone && $where['mobile'] = $phone;
//
//        ($status==='0'||$status==='1' ) && $where['status'] = $status;
//        $start_time && $where['created_at'] = ['>',$start_time];
//        $start_time && $end_time && $where['created_at'] = ['between',[$start_time,$end_time]];

        $list = User::select('id','name','nickname','mobile','header_img','created_at')
            ->where($where)->withCount('order_count')->orderBy('id','desc')->paginate($request->pageSize?:15);


        return $this->success($list);

    }

    //编辑用户信息
    public function editUser(Request $request){
        $status = $request->status; //用户状态

        $user_id = $request->user_id;
        $reason = $request->reason;

        if(!$user_id)
            return $this->failed('参数不全');

        $res = DB::table('users')->where('id',$user_id)->update(['reason'=>$reason,'status'=>$status,'status_time'=>date("Y-m-d H:i:s",time())]);

        return $this->success("编辑成功");

    }


    //获取用户信息详情
    public function getUserInfo(Request $request){


        $user_id = $request->user_id;

        if(!$user_id)
            return $this->failed('参数不全');

        $res = User::where('id',$user_id)->withCount('order')->with("order1:user_id,created_at")->first();
        $res->region_lng = '';
        $res->region_lat = '';
        $res->region_name = '';
        if($res->region_id){
            $region = DB::table('region')->find($res->region_id);
            $res->region_lng = $region->longitude;
            $res->region_lat = $region->latitude;
            $res->region_name = $region->name;
        }


        return $this->success($res);

    }






}
